<template>
    <view class="container">
        <!-- Info Items -->
        <view class="info-form bg-f bor-r-20">
            <view class="divide-y divide-gray-100">
                <!-- 头像 -->
                <view class="f f-bt info-items info-avatar">
                    <text class="f-col f-c c-3 fs-30">头像</text>
                    <view class="f f-c">
                        <!-- #ifdef MP-WEIXIN -->
                        <!-- 微信小程序使用 chooseAvatar -->
                        <button
                            class="avatar-wrapper unset-btn"
                            open-type="chooseAvatar"
                            @chooseavatar="onChooseAvatar"
                        >
                            <image class="avatar-image" :src="userForm.user_avatar"></image>
                        </button>
                        <!-- #endif -->
                        <!-- #ifdef H5 -->
                        <!-- H5 使用点击事件触发图片选择 -->
                        <view class="avatar-wrapper" @click="chooseImage">
                            <image class="avatar-image" :src="userForm.user_avatar"></image>
                        </view>
                        <!-- #endif -->
                        <view class="f-col f-c ml-10">
                            <uni-icons type="right" color="#999" size="18"></uni-icons>
                        </view>
                    </view>
                </view>

                <!-- 姓名（使用 nickname 类型） -->
                <view class="f f-bt info-items">
                    <text class="c-3 fs-30">姓名</text>
                    <view class="f f-c">
                        <view class="f-col f-c t-c">
                            <input
                                type="nickname"
                                class="c-3 fs-30 t-r"
                                v-model="userForm.user_name"
                                placeholder="请输入姓名"
                            />
                        </view>
                    </view>
                </view>

                <!-- 性别 -->
                <view class="f f-bt info-items" @click="selectSex">
                    <text class="c-3 fs-30">性别</text>
                    <view class="f f-c">
                        <view class="f-col f-c t-c">
                            <view class="uni-input c-3 fs-30">{{
                                sexArray[userForm.user_sex - 1] || '请选择'
                            }}</view>
                        </view>
                        <view class="f-col f-end ml-10">
                            <uni-icons type="right" color="#999" size="18"></uni-icons>
                        </view>
                    </view>
                </view>

                <!-- 出生日期 -->
                <view class="f f-bt info-items" @click="openCalendar">
                    <text class="c-3 fs-30">出生日期</text>
                    <view class="f f-c">
                        <view class="f-col f-c t-c">
                            <text class="c-3 fs-30">{{ userForm.user_birth || '请选择' }}</text>
                        </view>
                        <view class="f-col f-end ml-10">
                            <uni-icons type="right" color="#999" size="18"></uni-icons>
                        </view>
                    </view>
                </view>

                <!-- 个人简介 -->
                <view class="f-col info-items">
                    <text class="c-3 fs-30 mb-20">个人简介</text>
                    <textarea
                        class="profile-textarea c-3 fs-30"
                        v-model="userForm.user_profile"
                        placeholder="请输入个人简介"
                        maxlength="200"
                    ></textarea>
                    <view class="t-r c-9 fs-24 mt-10">{{ userForm.user_profile.length }}/200</view>
                </view>
            </view>
        </view>

        <!-- 保存按钮 -->
        <view class="save-btn-container">
            <button class="save-btn" @click="saveUserInfo">保存</button>
        </view>

        <!-- 日期选择器 -->
        <uni-calendar
            ref="calendar"
            :insert="false"
            :end-date="getCurrentDate()"
            @confirm="dateConfirm"
        />
    </view>
</template>

<script>
import { mapState } from 'pinia';
import useUserStore from '@/stores/modules/user';
import _ from 'lodash';
import login from '@/common/login';
import { uploadImage, updateBaseInfo } from '@/api/modules/common';

export default {
    computed: {
        // 使用 mapState 辅助函数将 store 中的状态映射为计算属性
        ...mapState(useUserStore, [
            'user_name',
            'user_avatar',
            'user_sex',
            'user_id',
            'user_birth',
            'user_profile'
        ])
    },
    data() {
        return {
            sexArray: ['男', '女'],
            userForm: {
                user_name: '',
                user_avatar: '',
                user_sex: 1,
                user_birth: '',
                user_profile: '',
                user_mobile: ''
            },
            isLoading: false
        };
    },
    onLoad() {
        // 初始化表单数据
        this.initFormData();
    },
    onShow() {
        const user_store = useUserStore();
        if (!_.isEmpty(user_store.token)) {
            this.initFormData();
            return;
        }
        // #ifdef H5
        // H5环境跳转到登录页
        uni.reLaunch({
            url: '/pages/login/login'
        });
        // #endif
        // #ifndef H5
        // 微信小程序调用微信登录
        login();
        // #endif
    },

    methods: {
        // 初始化表单数据
        initFormData() {
            this.userForm = {
                user_name: this.user_name || '',
                user_avatar: this.user_avatar || '',
                user_sex: this.user_sex || 1,
                user_birth: this.user_birth || '',
                user_profile: this.user_profile || '',
                user_mobile: this.user_mobile || ''
            };
        },

        // 选择头像（微信小程序 chooseAvatar 回调）
        onChooseAvatar(e) {
            const { avatarUrl } = e.detail || {};
            if (!avatarUrl) return;
            this.uploadAvatar(avatarUrl);
        },

        // H5 环境选择图片
        chooseImage() {
            uni.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: res => {
                    const filePath = res.tempFilePaths[0];
                    this.uploadAvatar(filePath);
                },
                fail: err => {
                    console.error('选择图片失败', err);
                    uni.showToast({
                        title: '选择图片失败',
                        icon: 'none'
                    });
                }
            });
        },

        // 上传头像
        async uploadAvatar(filePath) {
            try {
                uni.showLoading({ title: '上传中...' });
                // 直接使用项目中的 uploadImage API，传入 filePath
                const { data } = await uploadImage(filePath);
                this.userForm.user_avatar = data.url;
                console.log('uploadAvatar', this.userForm.user_avatar);
            } catch (err) {
                console.error('上传失败', err);
                uni.showToast({
                    title: '头像上传失败',
                    icon: 'none'
                });
            } finally {
                console.log('finally');
                uni.hideLoading();
            }
        },

        // 选择性别
        selectSex() {
            uni.showActionSheet({
                itemList: this.sexArray,
                success: res => {
                    this.userForm.user_sex = res.tapIndex + 1;
                }
            });
        },

        // 打开日历选择器
        openCalendar() {
            this.$refs.calendar.open();
        },

        // 日期确认
        dateConfirm(e) {
            this.userForm.user_birth = e.fulldate;
        },

        // 获取当前日期
        getCurrentDate() {
            const date = new Date();
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            return `${year}-${month}-${day}`;
        },

        // 保存用户信息
        async saveUserInfo() {
            if (!this.userForm.user_name) {
                uni.showToast({ title: '请输入姓名', icon: 'none' });
                return;
            }

            if (this.isLoading) return;
            this.isLoading = true;

            try {
                uni.showLoading({ title: '保存中...' });
                const { data } = await updateBaseInfo(this.userForm);
                // 更新本地存储的用户信息
                const user_store = useUserStore();
                user_store.modifyUserData(data);
                uni.showToast({ title: '保存成功', icon: 'success' });
            } catch (err) {
                console.error('保存失败', err);
                uni.showToast({ title: err?.msg || '网络异常，请稍后重试', icon: 'none' });
            } finally {
                uni.hideLoading();
                this.isLoading = false;
            }
        }
    }
};
</script>

<style lang="scss" scoped>
page {
    background-color: #f5f7fa;
}

.container {
    padding: 20rpx 30rpx 120rpx;
    min-height: 100vh;
}

.info-form {
    overflow: hidden;
}

.info-items {
    border-bottom: 2rpx solid #eee;
    padding: 30rpx 20rpx;
}

.info-avatar {
    padding: 20rpx;

    .avatar-image {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        border: 2rpx solid #eee;
    }
}

.profile-textarea {
    width: 100%;
    height: 200rpx;
    background-color: #f8f9fa;
    border-radius: 10rpx;
    padding: 20rpx;
    box-sizing: border-box;
}

.save-btn-container {
    position: fixed;
    bottom: env(safe-area-inset-bottom);
    left: 0;
    right: 0;
    padding: 20rpx 30rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.save-btn {
    background-color: #3b82f6;
    color: #fff;
    border-radius: 50rpx;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 32rpx;
    font-weight: 500;
}

.avatar-wrapper {
    padding: 0;
    margin: 0;
    border: none;
    background: transparent;
    border-radius: 0;
    width: auto;
    height: 100rpx;
    /* #ifdef H5 */
    cursor: pointer;
    /* #endif */
}

.avatar-wrapper::after {
    border: none;
}
</style>
